package com.stx.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.stx.entity.Department;
import com.stx.jdbc.JdbcUtil;

public class DepartmentDao {
	public List<Department> getAlldepartment(){
		Connection con = null;
		PreparedStatement pst = null;
		List<Department> deplist = new ArrayList<Department>();
		try {
			con = JdbcUtil.getCon();
			pst = con.prepareStatement("select *from tbl_department");
			ResultSet rs = pst.executeQuery();
			while (rs.next()){
				
				Department department = new Department();
				department.setdId(rs.getString("did"));
				System.out.println("hahah!");
				department.setDname(rs.getString("dname"));
				department.setDaddress(rs.getString("daddress"));
				department.setDphone(rs.getString("dphone"));
				deplist.add(department);
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}finally {
			JdbcUtil.closeCon(con, pst);
		}
		
		return deplist;
	}
	public boolean addDepartment(String dname,String daddress,String dphone){
		Connection con = null;
		PreparedStatement pst = null;
		try {
			con=JdbcUtil.getCon();
			pst=con.prepareStatement("select dname,did from tbl_department where dname=?");
			pst.setString(1, dname);
			ResultSet rs = pst.executeQuery();
			if(rs.next()){
				return false;
			}else{
			pst=con.prepareStatement("insert into tbl_department values(seq_department.nextval,?,?,?)");
			pst.setString(1, dname);
			pst.setString(2, daddress);
			pst.setString(3, dphone);
			pst.executeUpdate();
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.closeCon(con, pst);
		}
		return true;
	}
	public boolean delDepartment(String did){
		Connection con=null;
		PreparedStatement pst=null;
		try {
			con = JdbcUtil.getCon();
			pst = con.prepareStatement("delete from tbl_department where did=?");
			pst.setString(1,did);
			pst.executeUpdate();
			return true;
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.closeCon(con, pst);
		}
		return false;
	}
}
